package task

import activity.MainActivity
import event.PaySuccessEvent
import ext.log
import manager.HttpRequestManager
import manager.PayManager


import org.greenrobot.eventbus.EventBus
import org.json.JSONObject
import popup.DeliveryWindow
import popup.PayWindow


class PayResultTask(private val param: JSONObject) : Runnable {
    override fun run() {
        try {
            val order = param.optString("out_trade_no")

            if (isGoodsTypeExist(order)) { // 已经出货过了
                log("$order:已经出货")
                return
            }

            if (isRefunded(order)) { // 已经退款
                log("$order:已经退款")
                return
            }

            if (order == PayManager.CurrentOrder) {
                if (DeliveryWindow.isShow) {
                    log("已经正在出货")
                    return
                }

                if (PayWindow.isShow) {
                    log("开始出货:$order")
                    EventBus.getDefault().post(PaySuccessEvent())
                } else {
                    HttpRequestManager.refundWithAlipay(order, "用户取消/超时后支付", "用户取消/超时后支付")
                    HttpRequestManager.refundWithWechat(order, "用户取消/超时后支付", "用户取消/超时后支付")
                }

            } else {
                HttpRequestManager.refundWithAlipay(order, "支付非当前订单", "支付非当前订单")
                HttpRequestManager.refundWithWechat(order, "支付非当前订单", "支付非当前订单")
            }

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun isRefunded(order: String): Boolean {
        val ret = HttpRequestManager.queryRefund(order)
        log("退款查询结果:$ret")
        val json = JSONObject(ret)
        val info = json.optInt("result", 0)
        return info > 0
    }

    private fun isGoodsTypeExist(order: String): Boolean {
        val ret = HttpRequestManager.queryOrder(order)
        log("货道查询结果:$ret")
        val json = JSONObject(ret)
        val info = json.optString("cargolane", "")
        return !info.isEmpty()
    }

}